use std::any::Any;
use log::info;
use tokio::sync::mpsc;
use rpc::connection_manager::event::{ConnectionEvent, ConnectionManageable};
use rpc::dto::{RpcHeader};
use rpc::{ChannelId, RpcResult};

#[tokio::test]
async fn send_test() -> RpcResult<()> {
    let (data_sender, mut data_receiver) = mpsc::unbounded_channel::<Box<dyn ConnectionEvent>>();

    let header = RpcHeader::new("/demo", "111".to_string(), 0);
    let data = Box::new(ConnectionSendDataEvent::SendData(ChannelId::new(0), header, "111".to_string().into_bytes()));
    data_sender.send(data).unwrap();
    let data = data_receiver.recv().await.unwrap();

    let as_any : Box<dyn Any> = data;
    if as_any.is::<ConnectionSendDataEvent>() {
        let event = as_any.downcast::<ConnectionSendDataEvent>().unwrap();
        match *event {
            ConnectionSendDataEvent::SendData(channel_id, _rpc_header, _data) => {
                info!("convert success!!!!!!!!!!, {:?}", channel_id)
            }
        }
    }

    Ok(())
}

#[derive(Debug)]
enum ConnectionSendDataEvent {
    SendData(ChannelId, RpcHeader, Vec<u8>),
}

impl ConnectionEvent for ConnectionSendDataEvent {
    fn handle(self, mut manager: &mut dyn ConnectionManageable) -> RpcResult<()> {
        manager.handle_event(Box::new(self));
        Ok(())
    }
}